using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace Brick
{
	public class gdk_pageView : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IEventSystemHandler
	{
		private ScrollRect rect;

		private float targethorizontal;

		private bool isDrag;

		private List<float> posList = new List<float>();

		private int currentPageIndex = -1;

		public Action<int> OnPageChanged;

		private bool stopMove = true;

		public float smooting = 4f;

		public float sensitivity;

		private float startTime;

		private float startDragHorizontal;

		private int childCount;

		private void Awake()
		{
			init();
		}

		private void init()
		{
			posList.Clear();
			rect = base.transform.GetComponent<ScrollRect>();
			float num = rect.content.rect.width - GetComponent<RectTransform>().rect.width;
			posList.Add(0f);
			childCount = rect.content.transform.childCount;
			for (int i = 1; i < rect.content.transform.childCount - 1; i++)
			{
				posList.Add(GetComponent<RectTransform>().rect.width * (float)i / num);
			}
			posList.Add(1f);
		}

		private void Update()
		{
			if (childCount != rect.content.transform.childCount)
			{
				init();
			}
			if (!isDrag && !stopMove)
			{
				startTime += Time.deltaTime;
				float num = startTime * smooting;
				rect.horizontalNormalizedPosition = Mathf.Lerp(rect.horizontalNormalizedPosition, targethorizontal, num);
				if (num >= 1f)
				{
					stopMove = true;
				}
			}
		}

		public void pageTo(int index)
		{
			if (index >= 0 && index < posList.Count)
			{
				rect.horizontalNormalizedPosition = posList[index];
				SetPageIndex(index);
			}
			else
			{
				UnityEngine.Debug.LogWarning("页码不存在");
			}
		}

		private void SetPageIndex(int index)
		{
			if (currentPageIndex != index)
			{
				currentPageIndex = index;
				if (OnPageChanged != null)
				{
					OnPageChanged(index);
				}
			}
		}

		public void OnBeginDrag(PointerEventData eventData)
		{
			isDrag = true;
			startDragHorizontal = rect.horizontalNormalizedPosition;
		}

		public void OnEndDrag(PointerEventData eventData)
		{
			float horizontalNormalizedPosition = rect.horizontalNormalizedPosition;
			horizontalNormalizedPosition += (horizontalNormalizedPosition - startDragHorizontal) * sensitivity;
			horizontalNormalizedPosition = ((!(horizontalNormalizedPosition < 1f)) ? 1f : horizontalNormalizedPosition);
			horizontalNormalizedPosition = ((!(horizontalNormalizedPosition > 0f)) ? 0f : horizontalNormalizedPosition);
			int num = 0;
			float num2 = Mathf.Abs(posList[num] - horizontalNormalizedPosition);
			for (int i = 1; i < posList.Count; i++)
			{
				float num3 = Mathf.Abs(posList[i] - horizontalNormalizedPosition);
				if (num3 < num2)
				{
					num = i;
					num2 = num3;
				}
			}
			SetPageIndex(num);
			targethorizontal = posList[num];
			isDrag = false;
			startTime = 0f;
			stopMove = false;
		}
	}
}

